package com.jxl.domain.handler.subject;

import com.jxl.common.enums.DeletedCodeEnum;
import com.jxl.common.enums.SubjectTypeEnum;
import com.jxl.domain.convert.SubjectAnswerConvert;
import com.jxl.domain.entity.SubjectAnswerBO;
import com.jxl.domain.entity.SubjectInfoBO;
import com.jxl.domain.entity.SubjectOptionBO;
import com.jxl.infra.basic.entity.SubjectRadio;
import com.jxl.infra.basic.service.SubjectRadioService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 单选策略
 */
@Component
public class RadioHandler implements SubjectTypeHandler{

    @Resource
    private SubjectRadioService subjectRadioService;

    @Override
    public SubjectTypeEnum getHandlerType() {
        return SubjectTypeEnum.RADIO;
    }

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        List<SubjectRadio> subjectRadioList = new LinkedList<>();
        List<SubjectAnswerBO> optionList = subjectInfoBO.getOptionList();
        if (CollectionUtils.isEmpty(optionList)) return;
        List<SubjectRadio> subjectRadios =
                SubjectAnswerConvert.INSTANCE.convertBOToSubjectInfo(optionList);
        subjectRadios.forEach(option->{
            SubjectRadio subjectRadio = new SubjectRadio();
            subjectRadio.setOptionContent(option.getOptionContent());
            subjectRadio.setIsCorrect(option.getIsCorrect());
            subjectRadio.setOptionType(option.getOptionType());
            subjectRadio.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
            subjectRadio.setSubjectId(subjectInfoBO.getSubjectId());
            subjectRadioList.add(subjectRadio);
        });
        //在进行插入
        subjectRadioService.insertBatch(subjectRadioList);
    }

    @Override
    public SubjectOptionBO query(Long id) {
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(id);
        subjectRadio.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
        List<SubjectRadio> query = subjectRadioService.query(subjectRadio);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        List<SubjectAnswerBO> list = new ArrayList<>();
        if (query!=null && query.size()!=0){
            query.forEach(subjectRadios->{
                SubjectAnswerBO subjectAnswerBO = new SubjectAnswerBO();
                subjectAnswerBO.setIsCorrect(subjectRadios.getIsCorrect());
                subjectAnswerBO.setOptionType(subjectRadios.getOptionType());
                subjectAnswerBO.setOptionContent(subjectRadios.getOptionContent());
                list.add(subjectAnswerBO);
            });
            subjectOptionBO.setOptionList(list);
        }
        return subjectOptionBO;
    }
}
